<?php

namespace App\Mobile\Controllers;

include base_path() . '/vendor/autoload.php';
use EasyWeChat\Foundation\Application;
use Auth;
use DB;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use App\Agent;
use App\User;
use App\Withdraw;
use App\PhoneValidate;
use App\RebateLog;
use App\PublicGemsLog;
use App\WxPublicUser;
use App\AgentActive;
use App\Club;
use App\ClubUser;

class AgentController extends Controller
{
    protected $config = [
        'debug' => true,
	    'app_id' => 'wx555be570d21859aa',
	    'secret' => 'f92678be7687d1e1b1471ca9c066f242',
        'token' => '',
    ];

	/**
	 * 我的代理
	 */
	public function mySon(Request $request, Agent $agent)
	{
		$keywords = $request->input('keywords');
		if ($agent->level == 1 || $agent->level == 2) {
			$title = "我的代理";
			$users = Agent::where(['pid' => $agent->id, 'status' => 1]);
			if ($keywords) {
				$users = $users->where(function($query) use ($keywords){
					$query->where('realname', 'like', '%'.$keywords.'%')->orWhere('mobile', 'like', '%'.$keywords.'%');
				});
			}
			$users = $users->orderBy('created_at', 'DESC')->get();
			return view('mobile.agent.myson', compact('users', 'title', 'agent', 'keywords'));
		} else {
			$title = "我的用户";
			$users = User::where(['daili_id' => $agent->id]);
			if ($keywords) {
				$users = $users->where(function($query) use ($keywords){
					$query->where('nickname', 'like', '%'.$keywords.'%');
				});
			}
			$users = $users->orderBy('created_at', 'DESC')->get();
			return view('mobile.agent.agentuser', compact('users', 'title', 'agent', 'keywords'));
		}
	}

	/**
	 * 二级代理下级代理列表
	 */
	public function secondAgentSon(Request $request, Agent $agent)
	{
		$keywords = $request->input('keywords');
		$title = "我的代理";
		$users = Agent::where(['pid' => $agent->id, 'status' => 1]);
		if ($keywords) {
			$users = $users->where(function($query) use ($keywords){
				$query->where('realname', 'like', '%'.$keywords.'%')->orWhere('mobile', 'like', '%'.$keywords.'%');
			});
		}
		$users = $users->orderBy('created_at', 'DESC')->get();
		return view('mobile.agent.secondAgentSon', compact('users', 'title', 'agent', 'keywords'));
	}

	/**
	 * [myUser 一级代理查看下级玩家]
	 * @param  Request $request [description]
	 * @param  Agent   $agent   [description]
	 * @return [type]           [description]
	 */
	public function myUser(Request $request, Agent $agent)
	{
		$keywords = $request->input('keywords');
		$title = "我的用户";
		$users = User::where(['daili_id' => $agent->id]);
		if ($keywords) {
			$users = $users->where(function($query) use ($keywords){
				$query->where('nickname', 'like', '%'.$keywords.'%')->orWhere('name', 'like', '%'.base64_encode($keywords).'%');
			});
		}
		$users = $users->orderBy('created_at', 'DESC')->get();
		return view('mobile.agent.myuser', compact('users', 'title', 'agent', 'keywords'));
	}

	/**
	 * [development description]
	 * @return [type] [description]
	 */
	public function development(Agent $agent)
	{
		$title = "邀请代理";
       	$app = new Application($this->config);
       	$link_url = '';
        $js = $app->js;
		if ($agent->level != 1) {
			$title = "邀请用户";
			if (!file_exists(public_path()."/qrcode/code_$agent->id.jpg")) {
				$result = $app->qrcode->forever('qrscene'.$agent->id);
				$url = $app->qrcode->url($result['ticket']);
				$content = file_get_contents($url);
				file_put_contents(public_path() . "/qrcode/code_$agent->id.jpg", $content);
			}
			$url = "http://om0fc1nij.bkt.clouddn.com/114444780993342900.jpg?watermark/3/text/".\Qiniu\base64_urlSafeEncode($agent->realname)."/font/5b6u6L2v6ZuF6buR/fill/".\Qiniu\base64_urlSafeEncode('#FFFFFF')."/fontsize/500/dissolve/100/dx/200/dy/20/gravity/NorthWest/image/".\Qiniu\base64_urlSafeEncode($agent->avatar)."/dissolve/100/dx/20/gravity/NorthWest/image/".\Qiniu\base64_urlSafeEncode('http://user.leyougame.cc/qrcode/code_'.$agent->id.'.jpg')."/dissolve/100/dx/65/dy/50/gravity/SouthEast/ws/0.25/text/".\Qiniu\base64_urlSafeEncode($agent->id)."/font/5b6u6L2v6ZuF6buR/fill/".\Qiniu\base64_urlSafeEncode('#FBF950')."/fontsize/500/dissolve/100/dx/320/dy/100/gravity/SouthEast/";
		} else {
			/*生成水印图片*/
			if (!file_exists(public_path().'/qrcode/cache_agent/inv_agent_'.$agent->id.'.png')) {
				$invite_url = 'http://user.leyougame.cc/mobile/share?aid='.$agent->id;
				\QrCode::format('png')->size('175')->margin(0)->generate($invite_url, public_path().'/qrcode/cache_agent/inv_agent_'.$agent->id.'.png');
			} 
			$url = "http://om0fc1nij.bkt.clouddn.com/844869404097277569.jpg?watermark/3/text/".\Qiniu\base64_urlSafeEncode($agent->realname)."/font/5b6u6L2v6ZuF6buR/fill/".\Qiniu\base64_urlSafeEncode('#FFFFFF')."/fontsize/500/dissolve/100/dx/200/dy/20/gravity/NorthWest/image/".\Qiniu\base64_urlSafeEncode('http://user.leyougame.cc/qrcode/cache_agent/inv_agent_'.$agent->id.'.png')."/dissolve/100/dx/65/dy/50/gravity/SouthEast/image/".\Qiniu\base64_urlSafeEncode($agent->avatar)."/dissolve/100/dx/20/gravity/NorthWest";
			$link_url = 'http://user.leyougame.cc/mobile/share?aid='.$agent->id;
		}

		return view('mobile.agent.share', compact('agent', 'title', 'url', 'js', 'link_url'));
	}

	/**
	 * 二级代理发展3级代理
	 */
	public function secondDevelopment(Agent $agent)
	{
		$title = "邀请代理";
		/*生成水印图片*/
		if (!file_exists(public_path().'/qrcode/second_agent/inv_agent_'.$agent->id.'.png')) {
			$invite_url = 'http://user.leyougame.cc/mobile/seconddvlp?aid='.$agent->id;
			\QrCode::format('png')->size('175')->margin(0)->generate($invite_url, public_path().'/qrcode/second_agent/inv_agent_'.$agent->id.'.png');
		} 
		$url = "http://om0fc1nij.bkt.clouddn.com/844869404097277569.jpg?watermark/3/text/".\Qiniu\base64_urlSafeEncode($agent->realname)."/font/5b6u6L2v6ZuF6buR/fill/".\Qiniu\base64_urlSafeEncode('#FFFFFF')."/fontsize/500/dissolve/100/dx/200/dy/20/gravity/NorthWest/image/".\Qiniu\base64_urlSafeEncode('http://user.leyougame.cc/qrcode/second_agent/inv_agent_'.$agent->id.'.png')."/dissolve/100/dx/65/dy/50/gravity/SouthEast/image/".\Qiniu\base64_urlSafeEncode($agent->avatar)."/dissolve/100/dx/20/gravity/NorthWest";

		return view('mobile.agent.seconddvlp', compact('agent', 'title', 'url'));
	}

	/**
	 * [developUser 1级代理发展玩家]
	 * @return [type] [description]
	 */
	public function developUser(Agent $agent)
	{
		$app = new Application($this->config);
		$js = $app->js;
		$title = "邀请用户";
		if (!file_exists(public_path()."/qrcode/first/code_$agent->id.jpg")) {
			$result = $app->qrcode->forever('qrscene'.$agent->id);
			$url = $app->qrcode->url($result['ticket']);
			$content = file_get_contents($url);
			file_put_contents(public_path() . "/qrcode/first/code_$agent->id.jpg", $content);
		}
		$url = "http://om0fc1nij.bkt.clouddn.com/114444780993342900.jpg?watermark/3/text/".\Qiniu\base64_urlSafeEncode($agent->realname)."/font/5b6u6L2v6ZuF6buR/fill/".\Qiniu\base64_urlSafeEncode('#FFFFFF')."/fontsize/500/dissolve/100/dx/200/dy/20/gravity/NorthWest/image/".\Qiniu\base64_urlSafeEncode($agent->avatar)."/dissolve/100/dx/20/gravity/NorthWest/image/".\Qiniu\base64_urlSafeEncode('http://user.leyougame.cc/qrcode/first/code_'.$agent->id.'.jpg')."/dissolve/100/dx/65/dy/50/gravity/SouthEast/ws/0.25/text/".\Qiniu\base64_urlSafeEncode($agent->id)."/font/5b6u6L2v6ZuF6buR/fill/".\Qiniu\base64_urlSafeEncode('#FBF950')."/fontsize/500/dissolve/100/dx/320/dy/100/gravity/SouthEast/";
		return view('mobile.agent.firstShare', compact('agent', 'title', 'url', 'js'));
	}

	/**
	 * [cash description]
	 * @return [type] [description]
	 */
	public function cash(Agent $agent)
	{
		$datas = Withdraw::where(['agent_id' => $agent->id])->get();//体现记录
		$logs = RebateLog::where(['daili_id' => $agent->id])->get();//提现明细

		return view('mobile.agent.mycash', compact('agent', 'datas', 'logs'));
	}

	/**
	 * [withdraw description]
	 * @return [type] [description]
	 */
	public function withdraw(Agent $agent)
	{
		return view('mobile.agent.withdraw', compact('agent'));
	}

	/**
	 * [doWithdraw description]
	 * @param  Request $request [description]
	 * @param  Agent   $agent   [description]
	 * @return [type]           [description]
	 */
	public function doWithdraw(Request $request, Agent $agent)
	{
        $validator = Validator::make($request->input(), [
            'mobile' => 'required|regex:/^1[34578][0-9]{9}$/',
            'code' => 'required',
            'money' => 'required|numeric|min:100',
            'remark' => 'max:100'
        ],[
            'mobile.required' => '手机号不能为空!',
            'mobile.regex' => '手机号错误!',
            'code.required' => '请填写验证码!',
            'money.required' => '提现金额不为空!',
            'money.numeric' => '提现金额为数字!',
            'money.min' => '提现金额不少于100!',
            'remark.max' => '备注不要超过100字'
        ]);
        $exist = PhoneValidate::where('phone', '=', $request->input('mobile'))->where('code', '=', $request->input('code'))->first();
		if (!$exist) {
	        $validator->after(function($validator){
	            $validator->errors()->add('code', '验证码错误!');
	        });
		}
		if ($request->input('money') > $agent->money) {
        	$validator->after(function($validator){
	            $validator->errors()->add('money', '余额不足!');
	        });
		}
		if ($validator->passes()) {
			$withdraw = new Withdraw;
			$withdraw->agent_id = $agent->id;
			$withdraw->money = $request->input('money');
			if ($request->input('remark')) {
				$withdraw->remark = $request->input('remark');
			}
			$agent->money -= $request->input('money');
			DB::beginTransaction();
	    	try{
	    		$withdraw->save();
	    		$agent->save();
	    		$exist->delete();
	        	DB::commit();

	        	return ['flag' => true];
	    	} catch (Exception $e) {
	    		DB::rollback();
	    		
	    		return back();
	    	}
		} else {
    		$errors = $validator->errors();
        	foreach ($errors->messages as $val) {
        		$error = $val[0];
        	}
        	return ['flag' => false, 'msg' => $error];	
		}	
	}

	/**
	 * [auditList description]
	 * @return [type] [description]
	 */
	public function auditList(Agent $agent, Request $request)
	{
		$keywords = $request->input('keywords');
		$datas = Agent::where(['pid' => $agent->id, 'status' => 0])->orderBy('created_at', 'DESC');
		if ($keywords) {
			$datas = $datas->where(function($query) use ($keywords){
				$query->where('realname', 'like', '%'.$keywords.'%')->orWhere('mobile', 'like', '%'.$keywords.'%');
			});
		}
		$datas = $datas->get();
		return view('mobile.agent.auditList', compact('datas', 'keywords', 'agent'));
	}

	/**
	 * [audit description]
	 * @return [type] [description]
	 */
	public function doAudit(Agent $agent)
	{	
		$my = Auth::guard('mobile')->user();
		return view('mobile.agent.doaudit', compact('agent', 'my'));
	}

	/**
	 * [passAudit description]
	 * @return [type] [description]
	 */
	public function passAudit(Agent $agent, Request $request)
	{
		$my = Auth::guard('mobile')->user();
		if ($request->input('status') == 1) {
	    	$validator = Validator::make($request->input(), [
	            'divide' => 'required|min:1|max:100|numeric',
	        ],[
	        	'divide.required' => '分成比例不为空',
	        	'divide.min' => '分成比例大于1',
	        	'divide.max' => '分成比例小于100',
	        	'divide.numeric' => '分成比例为整数'
	        ]);
	    	if ($validator->passes()) {
	    		$agent->status = 1;
	    		$agent->divide = $request->input('divide');
	    		$agent->pass_time = time();
	    		$agent->save();
	    		$user = $agent->user();
        		/*自动创建俱乐部*/
        		$club = new Club;
        		$club->club_id = str_pad(mt_rand(1, 999999), 5, '0', STR_PAD_LEFT);
        		$club->club_name = base64_encode(base64_decode($user->name)."的亲友圈");
        		$club->creator = $user->userid;
        		$club->create_time = time();
        		$club->hotpush = 1;
        		$club->description = base64_decode($user->name)."的亲友圈";
        		$club->maxrooms = 5;
        		$club->club_fangfei = 0;
        		$club->limitpeople = 30;
        		$club->type = 1;
        		$club->save();
        		$club_user = new ClubUser;
        		$club_user->club_id = $club->club_id;
        		$club_user->userid = $user->userid;
        		$club_user->join_time = time();
        		$club_user->state = 999;
        		$club_user->save();

		        $app = new Application($this->config);
	            $notice = $app->notice;
	            $userService = $app->user;
	            $member = $userService->get($agent->open_id);
	            $subscribe = $member->subscribe;
	            if ($subscribe) {
		            $openId = $agent->open_id;
		            $templateId = 'q3kyGYoZalQ0fpCF57ipnMO__mwnoXLrZOSZOSQBjDY';
		            $url = url("/mobile/index");
		            $data = array(
		                "first" => "恭喜您通过了推广员审核，并为您开启了亲友圈!",
		                "keyword1" => "审核通过",
		                "keyword2" => "乐游手游推广员申请",
		                "keyword3" => date('Y-m-d H:i', $agent->shenqing_time),
		                "keyword4" => date('Y-m-d H:i', $agent->pass_time),
		                "remark" => "开启乐游之旅!",
		            );
		            $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($openId)->send();
	            }
	    		return redirect('/mobile/agent/audit_list/'.$my->id);
	    	} else {
	    		return Redirect::back()->withInput()->withErrors($validator->errors());
	    	}	
		} else {
			$agent->status = 2;
			$agent->reject_reason = $request->input('reject_reason');
			$agent->save();
			return redirect('/mobile/agent/audit_list/'.$my->id);
		}
	}

	/**
	 * [myParent description]
	 * @return [type] [description]
	 */
	public function myParent(Agent $agent)
	{
		return view('mobile.agent.myparent', compact('agent'));
	}

	/**
	 * [editDivide description]
	 * @return [type] [description]
	 */
	public function editDivide(Agent $agent)
	{
		$my = Auth::guard('mobile')->user();
		return view('mobile.agent.editDivide', compact('agent', 'my'));
	}

	/**
	 * [storeDivide description]
	 * @return [type] [description]
	 */
	public function storeDivide(Agent $agent, Request $request)
	{
        $validator = Validator::make($request->input(), [
            'divide' => 'required|numeric|max:100|min:0'
        ],[
        	'divide.required' => '分成比例不能为空',
        	'divide.numeric' => '分成比列为整数',
        	'divide.min' => '分成比例不少于0',
        	'divide.max' => '分成比例不大于100'
        ]);
        $my = Auth::guard('mobile')->user();
        if ($validator->passes()) {
        	$agent->divide = $request->input('divide');
        	$agent->save();
        	if ($agent->level == 3) {
        		return redirect('/mobile/agent/second_agent_son/'.$my->id);
        	} else {
        		return redirect('/mobile/agent/my_son/'.$my->id);
        	}
        } else {
        	return Redirect::back()->withInput()->withErrors($validator->errors());
        }
	}

	/**
	 * [firstCard description]
	 * @return [type] [description]
	 */
	public function firstCard(Agent $agent)
	{
		$my = Auth::guard('mobile')->user();
		return view('mobile.agent.firstcard', compact('agent', 'my'));
	}

	/**
	 * [storeFirstCard description]
	 * @param  Agent   $agent   [description]
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	public function storeFirstCard(Agent $agent, Request $request)
	{
        $validator = Validator::make($request->input(), [
            'gems' => 'required|numeric|min:1'
        ],[
        	'gems.required' => '请填写房卡数量',
        	'gems.numeric' => '房卡数量只能为整数',
        	'gems.min' => '房卡数量不少于1'
        ]);	
        $my = Auth::guard('mobile')->user();
        $user = $my->user();
        if ($request->input('gems') > $user->gems) {
	        $validator->after(function($validator){
	            $validator->errors()->add('gems', '您的房卡不足!');
	        });
        }
        if ($validator->passes()) {
        	$user->gems -= $request->input('gems');
        	$agent_user = $agent->user();
        	$agent_user->gems += $request->input('gems');
        	$log = new publicGemsLog;
        	if ($agent->level == 3) {
        		$log->type = 4;
        	} else {
        		$log->type = 2;
        	}
        	$log->send_id = $my->id;
        	$log->accept_id = $agent->id;
        	$log->gems = $request->input('gems');
			DB::beginTransaction();
	    	try{
	    		$user->save();
	    		$agent_user->save();
	    		$log->save();
	        	DB::commit();

	    		if ($agent->level == 3) {
	        		return redirect('/mobile/agent/second_agent_son/'.$my->id);
	        	} else {
	        		return redirect('/mobile/agent/my_son/'.$my->id);
	        	}
	    	} catch (Exception $e) {
	    		DB::rollback();
	    		
	        	if ($agent->level == 3) {
	        		return redirect('/mobile/agent/second_agent_son/'.$my->id);
	        	} else {
	        		return redirect('/mobile/agent/my_son/'.$my->id);
	        	}
	    	}
        } else {
        	return Redirect::back()->withInput()->withErrors($validator->errors());
        }
    }

    /**
     * [firstLog description]
     * @return [type] [description]
     */
    public function firstLog(Agent $agent)
    {
    	$my = Auth::guard('mobile')->user();
    	$logs = PublicGemsLog::where(['send_id' => $my->id, 'accept_id' => $agent->id])->orderBy('created_at', 'DESC')->get();
    	return view('mobile.agent.firstlog', compact('logs'));
    }

    /**
     * [secondCard description]
     * @return [type] [description]
     */
    public function secondCard(User $user)
    {
    	$my = Auth::guard('mobile')->user();
    	return view('mobile.agent.secondcard', compact('my', 'user'));
    }

    /**
     * [storeSecondCard description]
     * @param  User    $user    [description]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function storeSecondCard(User $user, Request $request)
    {
        $validator = Validator::make($request->input(), [
            'gems' => 'required|numeric|min:1'
        ],[
        	'gems.required' => '请填写房卡数量',
        	'gems.numeric' => '房卡数量只能为整数',
        	'gems.min' => '房卡数量不少于1'
        ]);	
        $my = Auth::guard('mobile')->user();
        $my_user = $my->user();
        if ($request->input('gems') > $my_user->gems) {
	        $validator->after(function($validator){
	            $validator->errors()->add('gems', '您的房卡不足!');
	        });
        }
        if ($validator->passes()) {
        	$my_user->gems -= $request->input('gems');
        	$user->gems += $request->input('gems');
        	$log = new publicGemsLog;
        	if ($my->pid == 0) {//1级代理给用户分配
        		$log->type = 3;
        	} else {//2级代理给用户分配
        		$log->type = 2;
        	}
        	$log->send_id = $my->id;
        	$log->accept_id = $user->id;
        	$log->gems = $request->input('gems');
			DB::beginTransaction();
	    	try{
	    		$my_user->save();
	    		$user->save();
	    		$log->save();
	        	DB::commit();
        		$unionid = substr($user->account, 3);
        		$wx_user = WxPublicUser::where(['unionid' => $unionid])->first();
        		if ($wx_user && $wx_user->openid) {
		        	$app = new Application($this->config);
		            $notice = $app->notice;
		            $openId = $wx_user->openid;
		            $userService = $app->user;
		            $member = $userService->get($openId);
		            $subscribe = $member->subscribe;
		            if ($subscribe) {
			            $templateId = 'CeF27UplYiFeRvLYlwEKdkJ5yiUI4TtObr6yvrGCaEA';
			            $url = '';
			            $data = array(
			                "first" => "您好，乐游推广员".$my->realname."赠送了您".$request->input('gems')."张银票",
			                "keyword1" => "银票",
			                "keyword2" => "已发送",
			                "remark" => "祝您游戏愉快!",
			            );
			            $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($openId)->send();
			        }
        		}
        		if ($my->pid == 0) {
		    		return redirect('/mobile/agent/my_user/'.$my->id);
		    	} else {
		    		return redirect('/mobile/agent/my_son/'.$my->id);
		    	}
	    	} catch (Exception $e) {
	    		DB::rollback();
	    		
        		if ($my->pid == 0) {
		    		return redirect('/mobile/agent/my_user/'.$my->id);
		    	} else {
		    		return redirect('/mobile/agent/my_son/'.$my->id);
		    	}	
	    	}
        } else {
        	return Redirect::back()->withInput()->withErrors($validator->errors());
        }
    }

    /**
     * [secondLog description]
     * @return [type] [description]
     */
    public function secondLog(User $user)
    {
    	$my = Auth::guard('mobile')->user();
    	$logs = PublicGemsLog::where(['send_id' => $my->id, 'accept_id' => $user->id])->orderBy('created_at', 'DESC')->get();
    	return view('mobile.agent.secondlog', compact('logs'));
    }

    /**
     * [openClub description]
     * @return [type] [description]
     */
    public function openClub(Agent $agent)
    {
    	return view('mobile.agent.openclub');
    }

    /**
     * [startClub description]
     * @return [type] [description]
     */
    public function startClub(Agent $agent)
    {
    	$user = $agent->user();
    	$user->agent = 1;
    	$user->save();
    	$my = Auth::guard('mobile')->user();
    	return redirect('/mobile/agent/my_son/'.$my->id);
    }

    /**
     * [myCash 我的佣金]
     * @return [type] [description]
     */
    public function myCash(Agent $agent)
    {
    	return view('mobile.agent.controlCash', compact('agent'));
    }

    /**
     * [withdrawLog 体现记录]
     * @param  Agent  $agent [description]
     * @return [type]        [description]
     */
    public function withdrawLog(Agent $agent)
    {
		$datas = Withdraw::where(['agent_id' => $agent->id])->orderBy('created_at', 'DESC')->get();//提现记录
		return view('mobile.agent.withdrawLog', compact('datas'));
    }

    /**
     * [rebateLog 佣金记录]
     * @param  Agent  $agent [description]
     * @return [type]        [description]
     */
    public function rebateLog(Agent $agent)
    {
    	if ($agent->level == 1) {
    		$datas = RebateLog::where(['second_id' => $agent->id])->groupBy('order_sn')->orderBy('created_at', 'DESC')->get();
    	} elseif ($agent->level == 2) {
    		$datas = RebateLog::where(['third_id' => $agent->id])->groupBy('order_sn')->orderBy('created_at', 'DESC')->get();
    	} elseif ($agent->level == 3) {
    		$datas = RebateLog::where(['fourth_id' => $agent->id])->groupBy('order_sn')->orderBy('created_at', 'DESC')->get();
    	}
    	return view('mobile.agent.rebateLog', compact('datas'));
    }

    /**
     * [income 收入管理]
     * @return [type] [description]
     */
    public function income(Agent $agent)
    {
    	$agents = Agent::where(['pid' => $agent->id])->get();
    	$users = User::where(['daili_id' => $agent->id])->get();
		return view('mobile.agent.income', compact('agent', 'agents', 'users'));
    }

    /**
     * [agentInfo 代理人详情]
     * @return [type] [description]
     */
    public function agentInfo(Agent $agent)
    {
    	$my = Auth::guard('mobile')->user();
    	if ($my->level == 1) {
    		if ($agent->level == 2) {
    			$datas = RebateLog::where(['second_id' => $my->id, 'third_id' => $agent->id, 'type' => 2])->orderBy('created_at', 'DESC')->get();
    		} elseif ($agent->level == 3) {
    			$datas = RebateLog::where(['second_id' => $my->id, 'fourth_id' => $agent->id, 'type' => 2])->orderBy('created_at', 'DESC')->get();
    		}
    	} elseif ($my->level == 2) {
			if ($agent->level == 3) {
    			$datas = RebateLog::where(['second_id' => $my->id, 'fourth_id' => $agent->id, 'type' => 2])->orderBy('created_at', 'DESC')->get();
    		}
    	}
    	return view('mobile.agent.agtinfo', compact('agent', 'my', 'datas'));
    }

    /**
     * [userInfo 玩家详情]
     * @param  User   $user [description]
     * @return [type]       [description]
     */
    public function userInfo(User $user)
    {
    	$my = Auth::guard('mobile')->user();
    	if ($my->level == 1) {
    		$datas = RebateLog::where(['second_id' => $my->id, 'user_id' => $user->userid, 'type' => 2])->orderBy('created_at', 'DESC')->get();
    	} elseif ($my->level == 2) {
    		$datas = RebateLog::where(['third_id' => $my->id, 'user_id' => $user->userid, 'type' => 3])->orderBy('created_at', 'DESC')->get();
    	} elseif ($my->level == 3) {
    		$datas = RebateLog::where(['fourth_id' => $my->id, 'user_id' => $user->userid, 'type' => 4])->orderBy('created_at', 'DESC')->get();
    	}
    	
    	return view('mobile.agent.userinfo', compact('user', 'my', 'datas'));
    }

    /**
     * [backHome description]
     * @return [type] [description]
     */
    public function backHome()
    {
    	$my = Auth::guard('mobile')->user();
    	return redirect('/mobile/agent/index/'.$my->id);
    }

    /**
     * [chargeActive 充值活动]
     * @return [type] [description]
     */
    public function chargeActive(Agent $agent)
    {
    	$actives = AgentActive::where(['agent_id' => $agent->id, 'type' => 1])->get();
    	return view('mobile.agent.chargeActive', compact('agent', 'actives'));
    }

    /**
     * [addActive 创建活动]
     */
    public function addActive(Request $request)
    {
    	if ($request->input('type') == 1) {//充值活动

    		return view('mobile.agent.addCharge');
    	} else {//自定义商品
    		

    	}
    }

    /**
     * [explain 分成说明]
     * @return [type] [description]
     */
    public function explain()
    {
    	return view('mobile.agent.explain');
    }

}